package live.ifox.stage;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.ID;
import live.ifox.factory.Profile;
import live.ifox.factory.Url;
import live.ifox.helper.AdapterHelper;
import live.ifox.helper.CustomProfile;

public class MainActivity extends BaseRestActivity {

    Spinner sp_category;
    SwipeRefreshLayout swipeLayout;
    ListView listView;
    CustomProfile profile;
    List<String> categories;
    String selectCategory;
    JSONArray array;
    int level;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actionBar.setDisplayHomeAsUpEnabled(false);

        level = 0;
        entry = Entry.Feedback;
        baseUrl = Url.Feedback;

        profile = new CustomProfile(this, Profile.User);
        level = profile.getInt("level");

        sp_category = findViewById(R.id.spinner);
        sp_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectCategory = categories.get(position);
                updateView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        listView = findViewById(R.id.listView);
        registerForContextMenu(listView);

        swipeLayout = findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            updateView();
        });

        updateCategory();
    }

    void updateCategory() {
        httpGet(baseUrl + "get_categories");
    }

    void updateView() {
        if (selectCategory != null && !selectCategory.isEmpty())
            httpGet(baseUrl + "by_category/" + selectCategory);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.ACTION_ADD, 0, "添加...");
        menu.add(0, ID.ACTION_UPDATE, 1, "更新类别");
        menu.add(0, ID.ACTION_ABOUT, 2, "关于");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ID.ACTION_ADD:
                startActivity(new Intent(this,
                        FeedbackEditor.class));
                return true;
            case ID.ACTION_UPDATE:
                updateCategory();
                return true;
            case ID.ACTION_ABOUT:
                startActivityForResult(new Intent(this,
                        AboutActivity.class)
                        .putExtra("level", level), ID.ACTION_ABOUT);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, ID.ACTION_EDIT, 0, "编辑...");
        menu.add(0, ID.ACTION_COPY, 1, "复制");
        menu.add(0, ID.ACTION_DO_FINISHED, 2, "已完成");
        if (level == 1)
            menu.add(0, ID.ACTION_REMOVE, 3, "删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (array == null || array.isEmpty())
            return false;

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        JSONObject object = array.getJSONObject(position);

        switch (item.getItemId()) {
            case ID.ACTION_EDIT:
                return do_editItem(object);
            case ID.ACTION_COPY:
                return do_copyItem(object, "detail");
            case ID.ACTION_DO_FINISHED:
                return do_finished(object);
            case ID.ACTION_REMOVE:
                return do_removeItem(object);
        }
        return super.onContextItemSelected(item);
    }

    boolean do_editItem(JSONObject object) {
        int id = object.getIntValue("id");
        String category = object.getString("category");
        String detail = object.getString("detail");
        if (id == 0 || category.isEmpty() || detail.isEmpty())
            return false;

        Intent intent = new Intent(this,
                FeedbackEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("category", category);
        intent.putExtra("detail", detail);
        startActivityForResult(intent, ID.FEEDBACK_EDITOR);
        return true;
    }

    boolean do_finished(JSONObject object) {
        return do_updateItem(object, "addition", "finished");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ID.RESULT_DONE) {
            switch (requestCode) {
                case ID.FEEDBACK_EDITOR:
                    if (categories == null || categories.isEmpty())
                        updateCategory();
                    else
                        updateView();
                    break;
                case ID.ACTION_ABOUT: {
                    if (data == null)
                        return;

                    level = data.getIntExtra("level", 0);
                    if (level == 1)
                        profile.putInt("level", level);
                    else
                        profile.remove("level");
                }
                break;
            }
        }
    }

    @Override
    public void processReply(JSONObject rootObject) {
        if (rootObject.containsKey("categories")) {
            JSONArray array = rootObject.getJSONArray("categories");
            categories = array.toJavaList(String.class);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_dropdown_item);
            adapter.addAll(categories);
            sp_category.setAdapter(adapter);
        } else if (rootObject.containsKey("detail")) {
            array = rootObject.getJSONArray("detail");
            if (array.isEmpty()) {
                listView.setAdapter(null);
                return;
            }
            List<Map<String, Object>> model = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                Map<String, Object> item = new HashMap<>();
                item.put("date_", object.getString("date_"));
                item.put("detail", object.getString("detail"));
                model.add(item);
            }
            if (!model.isEmpty()) {
                SimpleAdapter adapter = AdapterHelper.getTableAdapter(this,
                        model, new String[]{"date_", "detail"});
                listView.setAdapter(adapter);
            }
        }
    }
}
